package com.javasm.mingming.login.jwt;

import com.javasm.mingming.common.utils.TokenUtil;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author javasm
 * @version 0.1
 * @className JwtFilter
 * @descriptioin:
 * @date 2025/1/13 15:55
 * @since jdk11
 */
public class JwtFilter extends AbstractAuthenticationProcessingFilter {

    public JwtFilter() {
        super(new AntPathRequestMatcher("/tokenlogin","POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("请求方式不对,必须是POSt,你的请求方式是:" + request.getMethod());
        }
        String jwtStr = request.getHeader(TokenUtil.Server_Token_Key);
        if (StringUtils.isEmpty(jwtStr)){
            throw new AuthenticationServiceException("Token为空");
        }
        JwtToken jwtToken = new JwtToken(jwtStr);
        //详情
        jwtToken.setDetails(this.authenticationDetailsSource.buildDetails(request));
        Authentication authenticate = this.getAuthenticationManager().authenticate(jwtToken);

        return authenticate;
    }
}
